from huaweicloudsdkcore.auth.credentials import GlobalCredentials
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkcdn.v1.region.cdn_region import CdnRegion
from huaweicloudsdkcdn.v1 import *
from api.extension import return_code


class HuaWeiCloudMiddleware(object):
    def __init__(self, ak, sk, region):
        self.ak = ak
        self.sk = sk
        self.region = region

    def create_client(self):
        credentials = GlobalCredentials(self.ak, self.sk)
        client = CdnClient.new_builder().with_credentials(
            credentials).with_region(CdnRegion.value_of(self.region)).build()
        return client

    def preheatCache(self, urlspath, client):
        try:
            request = CreatePreheatingTasksRequest()
            preheatingTaskPreheatingTaskRequestBody = PreheatingTaskRequestBody(
                urls=urlspath)
            request.body = PreheatingTaskRequest(
                preheating_task=preheatingTaskPreheatingTaskRequestBody)
            response = client.create_preheating_tasks(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)

    def refreshCache(self, urlspath, client):
        try:
            request = CreateRefreshTasksRequest()
            refreshTaskRefreshTaskRequestBody = RefreshTaskRequestBody(
                urls=urlspath)
            request.body = RefreshTaskRequest(
                refresh_task=refreshTaskRefreshTaskRequestBody)
            response = client.create_refresh_tasks(request)
            return response
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
